﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Protocol;

namespace DAQ.MqttModule
{
    public class MqttControllor
    {
        private MqttConfig _config;
        private string _clientId;
        MqttClientOptions _clientOptions;

        private IMqttClient _mqttClient;

        public MqttControllor(MqttConfig config, string clientId = "")
        {
            _config = config;
            _clientId = config.ClientId == "" ? Guid.NewGuid().ToString() : config.ClientId;
            MqttClientOptionsBuilder optionsBuilder = new MqttClientOptionsBuilder()
                .WithTcpServer(_config.Ip, _config.Port)
                .WithCredentials(_config.Username, _config.Password)
                .WithClientId(_clientId);

            _clientOptions = optionsBuilder.Build();

            _mqttClient = new MqttFactory().CreateMqttClient();

            // 客户端连接关闭事件
            _mqttClient.DisconnectedAsync += MqttClient_DisconnectedAsync;
        }

        public void MqttConnect()
        {
            _mqttClient.ConnectAsync(_clientOptions).GetAwaiter().GetResult();
        }

        private Task MqttClient_DisconnectedAsync(MqttClientDisconnectedEventArgs arg)
        {
            Console.WriteLine($"客户端已断开与服务端的连接……");
            _mqttClient = new MqttFactory().CreateMqttClient();
            while (!_mqttClient.IsConnected)
            {
                Console.WriteLine($"正在重新连接……");
                MqttConnect();
                Task.Delay(1000).Wait();
            }
            return Task.CompletedTask;
        }

        /// <summary>
        /// 推送消息
        /// </summary>
        /// <param name="topic">主题</param>
        /// <param name="data">消息内容</param>
        /// <param name="qsLevel"></param>
        /// <param name="retain"></param>
        public void Publish(string topic, string data, int qsLevel = 0, bool retain = false)
        {
            if (qsLevel > 2)
            {
                qsLevel = 2;
            }
            if (qsLevel < 0)
            {
                qsLevel = 0;
            }

            var message = new MqttApplicationMessage
            {
                Topic = topic,
                PayloadSegment = Encoding.Default.GetBytes(data),
                QualityOfServiceLevel = (MqttQualityOfServiceLevel)qsLevel,
                Retain = retain // 服务端是否保留消息。true为保留，如果有新的订阅者连接，就会立马收到该消息。
            };
            _mqttClient.PublishAsync(message);
        }
    }
}
